package plus.easydo.starter.jpa.base;


import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import plus.easydo.core.base.controller.BaseController;
import plus.easydo.core.constant.HttpStatus;
import plus.easydo.core.result.DataResult;
import plus.easydo.core.result.R;
import plus.easydo.utils.ResultBeanUtil;
import plus.easydo.utils.ServletUtil;

import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * jpa部分通用web处理层
 * @author yuzhanfeng
 */
public class JpaBaseController extends BaseController {

    private static final String SUCCESS = "查询成功";


    /**
     * 获得分页
     * @param sort sort
     * @author yuzhanfeng
     * date 2021/5/2 17:08
     * @return org.springframework.data.domain.Pageable
     */
    public Pageable startPage(Sort sort) {
        int page = ServletUtil.getParameter("pageNum", 1);
        int limit = ServletUtil.getParameter("pageSize", 10);
        return PageRequest.of(page - 1, limit, sort);
    }

    /**
     * 获得分页
     * @author yuzhanfeng
     * date 2021/5/2 17:08
     * @return org.springframework.data.domain.Pageable
     */

    public Pageable startPage() {
        int page = ServletUtil.getParameter("pageNum", 1);
        int limit = ServletUtil.getParameter("pageSize", 10);
        return PageRequest.of(page - 1, limit);
    }

    /**
     * 返回表格数据
     * @param page page
     * @param target target
     * @param <A> 泛型
     * @param <B> 泛型
     * @author yuzhanfeng
     * date 2021/5/2 17:08
     * @return java.lang.Object
     */

    public <A, B> R<List<A>> resultTable(Page<B> page, Supplier<A> target) {
        List<A> list = null;
        if (null != page) {
            list = ResultBeanUtil.copyListProperties(page.getContent(), target);
        }
        DataResult<List<A>> result = DataResult.ok();
        result.setData(Objects.isNull(list) ? null : list);
        result.setMsg(SUCCESS);
        result.setCode(HttpStatus.SUCCESS);
        return result;
    }

    /**
     * 返回表格数据
     * @param page page
     * @param <T> 泛型
     * @author yuzhanfeng
     * date 2021/5/2 17:09
     * @return TableResult
     */

    protected <T> R<List<T>> resultTable(Page<T> page) {
        DataResult<List<T>> result = DataResult.ok();
        result.setData(Objects.isNull(page) ? null : page.getContent());
        return result;
    }


}
